package main

import (
	"fmt"
	"os"
	"sync"
	"sync/atomic"
)

// 定义数据结构
type Counter struct {
	count int64
}

func newCounter() *Counter {
	return &Counter{count: 0}
}

func (c *Counter) Increment() {
	atomic.AddInt64(&c.count, 1)
}

func (c *Counter) Decrement() {
	atomic.AddInt64(&c.count, -1)
}

func (c *Counter) GetCount() int64 {
	return atomic.LoadInt64(&c.count)
}

func (c *Counter) Reset() {
	atomic.StoreInt64(&c.count, 0)
}

func (c *Counter) WriteToFile(filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = file.WriteString(fmt.Sprintf("Counter value: %d\n", c.GetCount()))
	if err != nil {
		return err
	}
	return nil
}

func main() {
	wg := sync.WaitGroup{}
	counter := newCounter()

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			counter.Increment()
		}()
	}
	wg.Wait()
	fmt.Println("Counter value:", counter.GetCount())

	counter.Reset()

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			counter.Decrement()
		}()
	}
	wg.Wait()
	fmt.Println("Counter value:", counter.GetCount())

	err := counter.WriteToFile("counter.txt")
	if err != nil {
		fmt.Println("Error writing to file:", err)
	}

	cs := &CounterWithStats{totalAcess: 10, Counter: Counter{count: 10}}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			cs.Increment()
		}()
	}
	wg.Wait()
	fmt.Println("Counter value:", cs.GetCount())
	fmt.Println("Total access:", cs.GetTotalAccess())

}

type CounterWithStats struct {
	Counter
	totalAcess int64
}

func (c *CounterWithStats) Increment() {
	atomic.AddInt64(&c.totalAcess, 1)
	c.Counter.Increment()
}

func (c *CounterWithStats) GetTotalAccess() int64 {
	return atomic.LoadInt64(&c.totalAcess)
}
